package com.quanshu.exchange.ui.gui.shop_store;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.GoodsEntity;
import com.quanshu.exchange.support.entity.UserEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.login.LoginActivity;
import com.quanshu.exchange.ui.gui.pay.AlipayActivity;
import com.quanshu.exchange.ui.gui.profile.AllOrderActivity;
import com.quanshu.exchange.ui.gui.profile.DeliveryAddressActivity;
import com.quanshu.exchange.ui.gui.profile.DialogShare;
import com.quanshu.exchange.ui.gui.profile.ShoppingCartActivity;
import com.quanshu.exchange.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 商城网页的二...级页面
 * Created by xiniu003 on 2018/3/21.
 */

public class ShopTwoActivity extends BaseActivity {

    @BindView(R.id.webView)
    WebView mWebview;
    WebSettings mWebSettings;
    private String localUrl;
    private DialogShare dialogShare;
    private Bitmap bitmap;
    private GoodsEntity goodsEntity;
    private String shareUrl;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int msgId = msg.what;
            if (msgId == 0x01) {
                doShareWeChat(goodsEntity, "weChat");
            } else if (msgId == 0x02) {
                doShareWeChat(goodsEntity, "friends");
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two_shop);
        ButterKnife.bind(this);
        getIntentData();
        initWebView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void getIntentData() {
        localUrl = getIntent().getStringExtra("url");
    }

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtil.print("==ShopTwoActivity===shouldOverrideUrlLoading====" + url);
            UserEntity userEntity = MyApplication.getInstance().getCurrentUser();
            if (userEntity == null) {
                Intent intent = new Intent(ShopTwoActivity.this, LoginActivity.class);
                startActivity(intent);
                return true;
            }
            if (url.contains("index/login/1")) {
                Intent intent = new Intent(ShopTwoActivity.this, LoginActivity.class);
                startActivity(intent);
                return true;
            }
            if (url.contains("goApp?order_id")) {
                Intent intent = new Intent(ShopTwoActivity.this, AllOrderActivity.class);
                startActivity(intent);
                return true;
            }
            if (url.contains("address/add")) {
                Intent intent = new Intent(ShopTwoActivity.this, DeliveryAddressActivity.class);
                intent.putExtra("FLAG", "flag");
                startActivityForResult(intent, 12);
                return true;
            }
            if (url.contains("goMyCart")) {
                Intent intent = new Intent(ShopTwoActivity.this, ShoppingCartActivity.class);
                startActivity(intent);
                return true;
            }
            if (url.contains("goods_share")) {
                shareUrl = url;
                int index = url.lastIndexOf("/") + 1;
                String goodsId = url.substring(index, url.length());
                NetClient.getInstance()
                        .getShopService(ShopInterface.class)
                        .getGoodsInfo(goodsId)
                        .compose(new BaseTransformer<>(ShopTwoActivity.this))
                        .subscribe(new BaseObserver<BaseResponse<GoodsEntity>>() {
                            @Override
                            public void onSuccess(BaseResponse<GoodsEntity> response) {
                                goodsEntity = response.getData();
                                if (goodsEntity != null) {
                                    goodsEntity.setGoods_id(goodsId);
                                    dialogShare = new DialogShare(ShopTwoActivity.this);
                                    dialogShare.show();
                                    dialogShare.getWeChatSubject().subscribe(aVoid -> {
                                        doDownLoadImg(goodsEntity, 0x01);
                                        dialogShare.dismiss();
                                    });
                                    dialogShare.getFriendsSubject().subscribe(aVoid -> {
                                        doDownLoadImg(goodsEntity, 0x02);
                                        dialogShare.dismiss();
                                    });
                                }
                            }
                        });
                return true;
            }
            if (url.contains("wxPayString")) {
                doWxPay(url);
                return true;
            }
            if (url.contains("aliPayString")) {
                doAliPay(url);
                return true;
            }
            if (url.contains("cattle_exchange_show/index?")) {
                finish();
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    private void initWebView() {
        mWebSettings = mWebview.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setDefaultTextEncodingName("UTF-8");
        mWebSettings.setTextSize(WebSettings.TextSize.NORMAL);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebview.setWebChromeClient(new MyWebChromeClient());
        mWebview.setWebViewClient(new MyWebViewClient());
        mWebview.loadUrl(localUrl);
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            LogUtil.print("=====onConsoleMessage====" + consoleMessage.message());
            if (consoleMessage.message().equals("cancel")) {
                if (mWebview.canGoBack()) {
                    mWebview.goBack();
                } else {
                    finish();
                }
            }
            return super.onConsoleMessage(consoleMessage);
        }
    }

    private void doDownLoadImg(GoodsEntity goodsEntity, int msgWhat) {
        this.goodsEntity = goodsEntity;
        Thread thread = new Thread(() -> {
            try {
                String imgUrl = Config.URL_HOST_SHOP + goodsEntity.getImg();
                bitmap = AppUtils.getBitmap(imgUrl);
                handler.sendEmptyMessage(msgWhat);
            } catch (Exception e) {
                e.printStackTrace();
                bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                handler.sendEmptyMessage(msgWhat);
            }
        });
        thread.start();
    }

    private void doShareWeChat(GoodsEntity goodsEntity, String type) {
        IWXAPI iwxapi = WXAPIFactory.createWXAPI(this, MyApplication.getInstance().getWX_ID(), false);
        WXWebpageObject webpage = new WXWebpageObject();
        String url = shareUrl + "/memberid/" + currentUser.getMemberid();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = goodsEntity.getName();
        msg.description = "售价:  ¥" + goodsEntity.getSell_price();
        if (bitmap != null) {
            msg.thumbData = AppUtils.getBitmapBytes(bitmap);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        if (type.equals("weChat")) {
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else if (type.equals("friends")) {
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }
        iwxapi.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void doWxPay(String payUrl) {
        currentUser = MyApplication.getInstance().getCurrentUser();
        if (currentUser == null) {
            Intent intent = new Intent(ShopTwoActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        Intent intent = new Intent(ShopTwoActivity.this, WXPayEntryActivity.class);
        intent.putExtra("url", payUrl);
        startActivity(intent);
    }

    private void doAliPay(String payUrl) {
        currentUser = MyApplication.getInstance().getCurrentUser();
        if (currentUser == null) {
            Intent intent = new Intent(ShopTwoActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        Intent intent = new Intent(ShopTwoActivity.this, AlipayActivity.class);
        intent.putExtra("url", payUrl);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!mWebview.canGoBack()) {
            finish();
        }
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebview.canGoBack()) {
            mWebview.goBack(); //goBack()表示返回WebView的上一页面
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 12) {
                mWebview.goBack(); //goBack()表示返回WebView的上一页面
            }
        }
    }
}
